
let db = require('../utils/DB');//数据库
let to = require('../utils/await-to-js');
let { SUCCESS, ERROR } = require('../utils/result');//结果
let { HOST } = require('../utils/CONSTANT');//主机名

/*
    最终需要如下格式的数据：
        [
            {
                8015e8de-d52d-457d-86f4-6e0c129b1ad2:[
                    {
                        id: 1,
                        flash_id: "8015e8de-d52d-457d-86f4-6e0c129b1ad2",
                        goods_id: "1300435150060100001",
                        image_url: "http://www.ujiuye.tech:3000/image_source/goods_loop_img/rBACW1s91F-ANw1CAADqAEfOePM979.jpg",
                        goods_name: "中腰八分喇叭裤77B1722050",
                        goods_price: 249,
                        assem_price: 155.63
                    },
                    ...
                ],
                time:15
            },
            {
                 6c547d64-5432-46d1-b08b-a24c87e330cf:[],
                time:16
            }
        ]
*/

//秒杀
function flashModel() {
    return async (req, res) => {
        let rst = await getFlashData();//获取数据库中的数据        
        if (rst.length > 0) {

            let s = new Set();//保存flash_id
            let arr=[];//保存返回给客户端的数据
            // 遍历所有的秒杀商品，获取flashId
            rst.forEach(item => {
                s.add(item.flash_id);
            });
            //遍历flash_id,构建秒杀场次数据
            [...s].forEach((item,index) => {
                let obj = {     //秒杀场次对象
                    [item]: [],     //秒杀场次id，对应的所有秒杀商品
                    time:null       //秒杀场次时间
                };
                //遍历数据源，找到item(秒杀id)对应的秒杀商品数据(本场次)
                rst.forEach(goods => {
                    if (goods.flash_id == item) {
                        obj[item].push(goods);//将本场次的秒杀商品加入对应数组
                    }
                });
                obj.time = new Date().getHours()+index;//当前时间(小时)
                arr.push(obj);
            });
            SUCCESS(res, arr)
        } else {
            ERROR(res, '秒杀失败', rst)
        }
        // err ? ERROR(res, '人气好货失败', err) : SUCCESS(res, data);
    }
}


async function getFlashData() {
    let [err, data] = await to(db.query(`SELECT a.id ,a.flash_id,b.goods_id,CONCAT(?,c.image_url) as image_url,c.goods_name,c.assem_price,c.goods_price FROM flash_sale as a
        LEFT JOIN flash_product as b
        ON a.flash_id=b.flash_id
        LEFT JOIN goods_list as c
        ON b.goods_id=c.goods_id`, [HOST]));
    return err ? err : data;
}

module.exports = flashModel;